package com.zf.fastexcel.utils.handler;

import cn.idev.excel.FastExcel;
import cn.idev.excel.metadata.Head;
import cn.idev.excel.write.handler.CellWriteHandler;
import cn.idev.excel.write.metadata.holder.WriteSheetHolder;
import cn.idev.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.util.*;

/**
 * 设置内容单元格的数据格式为指定格式，针对指定列的内容行生效，跳过指定表头行
 */
public class CustomContentCellDataFormatWriteHandler implements CellWriteHandler {

    /**
     * 每列对应的格式，Excel内置格式可以在 {@link org.apache.poi.ss.usermodel.BuiltinFormats#_formats} 中查看，也可以自定义。
     * 列索引(>=0) -> 数据格式
     */
    private final Map<Integer, String> columnStyleMap = new LinkedHashMap<>();

    /**
     * 头行数
     */
    private int headerRowNumber = 0;

    public CustomContentCellDataFormatWriteHandler(Map<Integer, String> columnStyleMap, int headerRowNumber) {
        this.columnStyleMap.putAll(Optional.ofNullable(columnStyleMap).orElse(Collections.emptyMap()));
        if (headerRowNumber >= 0) {
            this.headerRowNumber = headerRowNumber;
        }
    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 跳过头行
        if (cell.getRowIndex() < headerRowNumber) {
            return;
        }
        String format = columnStyleMap.get(cell.getColumnIndex());
        if (StringUtils.isBlank(format)) {
            return;
        }
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        DataFormat dataFormatter = workbook.createDataFormat();

        // 方式1
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.cloneStyleFrom(cell.getCellStyle());
        cellStyle.setDataFormat(dataFormatter.getFormat(format));
        cell.setCellStyle(cellStyle);

        // 方式2: 目前这种方式导出的Excel在某些版本的office中，编辑时背景色会有问题
        // CellUtil.setCellStyleProperty(cell, CellUtil.DATA_FORMAT, dataFormatter.getFormat(format));
    }


    public static void main(String[] args) {
        // 表头
        List<List<String>> headers = new ArrayList<>();
        headers.add(Collections.singletonList("表头1"));
        headers.add(Collections.singletonList("表头2"));
        headers.add(Collections.singletonList("表头3"));

        // 列样式
        HashMap<Integer, String> columnStyleMap = new HashMap<>();
        columnStyleMap.put(0, "@"); // 文本
        columnStyleMap.put(1, "yyyy-mm-dd"); // 日期
        columnStyleMap.put(2, "@");

        // 一行数据
        HashMap<Integer, String> oneRow = new HashMap<>();
        oneRow.put(0, "111");
        oneRow.put(1, "2025-12-10");

        FastExcel.write(new File("D:\\test.xlsx"))
                .sheet(0)
                .head(headers)
                .registerWriteHandler(new CustomContentCellDataFormatWriteHandler(columnStyleMap, 1))
                .doWrite(Collections.singletonList(oneRow));
    }


}
